import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * servlet程序
 */
public class ServletTest implements Servlet {
    /**
     * Serblet的构造器方法
     */
    public ServletTest(){
        System.out.println("1   Servlet程序的构造器方法");
    }
    /**
     * init初始化方法
     * @param servletConfig
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("2   init初始化方法");
        System.out.println(servletConfig.getServletName());
    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }


    /**
     * service方法是用来处理请求和响应的
     * @param servletRequest
     * @param servletResponse
     * @throws ServletException
     * @throws IOException
     */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
//        System.out.println("3   客户端访问了");
        // getMethod()方法只有servletRequest接口的子类，所以要进行类型转换
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        // 下面代码进行了Servlet请求的分发处理
        String method = httpServletRequest.getMethod();
        if ("GET".equals(method)){
            // 为了方便后期的维护和简洁，将内容放到方法里面
            doGET();
        }else if ("POST".equals(method)){
            doPOST();
        }
        HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;
        httpServletResponse.setHeader("name", "haojq");
    }
    private void doPOST() {
        System.out.println("POST请求");
        System.out.println("POST请求");
    }
    private void doGET() {
        System.out.println("GET请求");
        System.out.println("GET请求");
    }
    @Override
    public String getServletInfo() {
        return null;
    }
    /**
     * 服务器关闭的时候调用的方法
     */
    @Override
    public void destroy() {
        System.out.println("4   结束的时候执行");
    }
}
